import React, { useEffect, useState } from 'react';
import { Button, Table, Tag, Space, message, Modal } from 'antd';
import { getDeptList, deleteDept, changeStatus } from './services';
import { Dept } from './type';
import DeptFormModal from './components/DeptFormModal';

const DepartmentPage: React.FC = () => {
  const [deptList, setDeptList] = useState<Dept[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentDept, setCurrentDept] = useState<Dept | null>(null);

  const loadData = async () => {
    setLoading(true);
    const res = await getDeptList();
    setDeptList(res.data);
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确定要删除该部门吗？',
      onOk: async () => {
        await deleteDept(id);
        message.success('删除成功');
        loadData();
      },
    });
  };

  const handleChangeStatus = async (record: Dept) => {
    const newStatus = record.status === '1' ? '0' : '1';
    await changeStatus(record.id, newStatus);
    message.success('状态更新成功');
    loadData();
  };

  const columns = [
    { title: '部门名称', dataIndex: 'deptName' },
    { title: '排序', dataIndex: 'orderNum' },
    { title: '负责人', dataIndex: 'leader' },
    { title: '电话', dataIndex: 'phone' },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: string) =>
        status === '1' ? <Tag color="green">正常</Tag> : <Tag color="red">停用</Tag>,
    },
    {
      title: '操作',
      render: (_: any, record: Dept) => (
        <Space>
          <a onClick={() => { setCurrentDept(record); setFormVisible(true); }}>编辑</a>
          <a onClick={() => handleDelete(record.id)}>删除</a>
          <a onClick={() => handleChangeStatus(record)}>
            {record.status === '1' ? '停用' : '启用'}
          </a>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={() => { setCurrentDept(null); setFormVisible(true); }}>新增</Button>
        <Button onClick={loadData}>刷新</Button>
      </Space>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={deptList}
        pagination={false}
      />
      <DeptFormModal
        open={formVisible}
        dept={currentDept}
        onCancel={() => setFormVisible(false)}
        onOk={() => { setFormVisible(false); loadData(); }}
      />
    </div>
  );
};

export default DepartmentPage;
